package com.wangzh.concurrent.lock.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUCA {

    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }

        }).start();
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }

        }).start();
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }).start();
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }).start();
    }

}

//判断等待，业务，通知
//通过JUC实现synchronized和Object.wait(),notifyAll()
class Data2 { //资源类
    private int number = 0;

    Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();

    //    +1
    public void increment() throws InterruptedException {


        lock.lock();
        try {
            while (number != 0) {
                //            判断
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + ",add:" + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }

    //    -1
    public void decrement() throws InterruptedException {
        lock.lock();

        try {

            while (number == 0) {
//            业务
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + ",de:" + number);
            condition.signalAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }


}
